package com.project.myapplication;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import java.io.IOException;

public class MyService extends Service {
    private MediaPlayer mp;
    private int progress;
    private Handler handler;
    private String url=null;
    public MyService() {
    }
    public void innit(){
        mp = new MediaPlayer();
        mp.reset();
        try {
            mp.setDataSource("/mnt/sdcard/mp3/ad.mp3");
            mp.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onCreate() {
        innit();
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                String info = msg.getData().getString("url");
                Log.i("hahah","..........qteqrtqer"+info);
                mp = new MediaPlayer();
                mp.reset();
                try {
                    mp.setDataSource(info);
                    mp.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };

    }
    public void play(){
        mp.start();
    }
    public void pause(){
        mp.pause();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       int action = intent.getIntExtra("action",-1);
       switch (action){
           case 1 :
               play();
               break;
           case 2:
               pause();
               break;
       }
        return super.onStartCommand(intent, flags, startId);
    }

    public class Mybinder extends Binder{

        public int getprogress(){
            return mp.getCurrentPosition();
        }
        public int getfulltime(){
            return  mp.getDuration();
        }
        public void gototime(int time){
            mp.seekTo(time);
        }
        public void changesong(String urll){
            mp.release();
            url =urll;
            Message msg = new Message();
            Bundle b = new Bundle();
            b.putString("url",url);
            msg.setData(b);
            handler.sendMessage(msg);
        }
    }
    @Override
    public IBinder onBind(Intent intent) {
        return new Mybinder();
    }
}
